import tableServiceAbstract from "@/core/table/tableService.interface";
import { $menuList, $menuDetail, $menuAdd, $menuEdit, $menuDelete } from "@/api/menu/menu";
export default class menuService implements tableServiceAbstract {
  getTable(params: any): Promise<any> {
    return new Promise((resolve) => {
      $menuList(params).then((res: any) => {
        const eachSort = (arr: any[]) => {
          arr = arr.sort((a, b) => a.order_num - b.order_num);
          arr.forEach((item: any) => {
            item.childlist?.length === 0 && (delete item.childlist);
            item.childlist?.length > 0 && eachSort(item.childlist);
          })
        }
        eachSort(res.data?.menu_list || []);
        resolve({
          data: this.handleTree(res.data?.all || [], "menu_id"),
        });
      })
    });
  }
  delete(params: any): Promise<any> {
    return $menuDelete(params);
  }
  add(params: any): Promise<any> {
    return $menuAdd(params);
  }
  edit(params: any): Promise<any> {
    return $menuEdit(params);
  }
  detail(params: any): Promise<any> {
    return $menuDetail(params);
  }
  // 树形结构构造
  handleTree(data: any, id: any, parentId?: any, children?: any) {
    let config = {
      id: id || 'id',
      parentId: parentId || 'parent_id',
      childrenList: children || 'childlist'
    };

    var childrenListMap: any = {};
    var nodeIds: any = {};
    var tree:any = [];

    for (let d of data) {
      let parentId = d[config.parentId];
      if (childrenListMap[parentId] == null) {
        childrenListMap[parentId] = [];
      }
      nodeIds[d[config.id]] = d;
      childrenListMap[parentId].push(d);
    }

    for (let d of data) {
      let parentId = d[config.parentId];
      if (nodeIds[parentId] == null) {
        tree.push(d);
      }
    }

    for (let t of tree) {
      adaptToChildrenList(t);
    }

    function adaptToChildrenList(o: any) {
      if (childrenListMap[o[config.id]] !== null) {
        o[config.childrenList] = childrenListMap[o[config.id]];
      }
      if (o[config.childrenList]) {
        for (let c of o[config.childrenList]) {
          adaptToChildrenList(c);
        }
      }
    }
    return tree;
  }
}
